package com.xd.clap.services.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xd.clap.entity.Admin;
import com.xd.clap.entity.request.LoginParam;
import com.xd.clap.entity.request.PageParam;
import com.xd.clap.entity.request.WxParam;
import com.xd.clap.entity.response.LoginResult;
import com.xd.clap.entity.response.Result;
import com.xd.clap.exception.ClapException;
import com.xd.clap.mapper.AdminMapper;
import com.xd.clap.services.AdminService;
import com.xd.clap.utils.JWTUtil;
import com.xd.clap.utils.LoginUtil;
import com.xd.clap.utils.MD5;
import com.xd.clap.utils.RedisUtil;
import com.xd.clap.utils.convenient.ConvenientUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class AdminServiceImpl implements AdminService {

    @Resource
    private AdminMapper am;

    @Resource
    private RedisUtil redisUtil;

    @Override
    public Result adminLogin(LoginParam loginParam) {
        // 返回结果集map
        Map<String, Object> resultMap = new HashMap<>();
        String code = loginParam.getCode();
        // 通过code获取手机号
        String phone = LoginUtil.getPhoneNumber(code);
        if (phone == null) {
            return Result.fail(100, "手机号获取失败！");
        }
        LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Admin::getPhone, phone);
        List<Admin> adminList = am.selectList(queryWrapper);
        List<String> addressList = new ArrayList<>();
        if (adminList.size() == 0) {
            LoginResult loginResult = new LoginResult();
            loginResult.setPhone(phone);
            loginResult.setName("群众");
            loginResult.setAddress("");
            loginResult.setAuthority("0");
            loginResult.setAddressList(addressList);
            // loginResult
            resultMap.put("loginResult", loginResult);
            // 生成token
            String token = JWTUtil.createToken(phone);
            resultMap.put("token", token);
            // 存入redis并设置过期时间为10天
            redisUtil.set("app-login:" + phone, loginResult, 10, TimeUnit.DAYS);
            return Result.success(resultMap, "success");
        }
        for (Admin admin : adminList) {
            addressList.add(admin.getAddress());
        }
        LoginResult loginResult = new LoginResult();
        loginResult.setPhone(phone);
        loginResult.setName(adminList.get(0).getName());
        loginResult.setAddress(adminList.get(0).getAddress());
        loginResult.setAuthority(adminList.get(0).getAuthority());
        loginResult.setAddressList(addressList);
        // loginResult
        resultMap.put("loginResult", loginResult);
        // 生成token
        String token = JWTUtil.createToken(phone);
        resultMap.put("token", token);
        // 存入redis并设置过期时间为10天
        redisUtil.set("app-login:" + phone, adminList.get(0), 10, TimeUnit.DAYS);
        return Result.success(resultMap, "success");
    }

    @Override
    public List<Admin> getAdminList(List<String> second_address) {
        List<Admin> adminList = new ArrayList<>();
        second_address.forEach(item -> {
            LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Admin::getAddress, item);
            Admin admin = am.selectOne(queryWrapper);
            adminList.add(admin);
        });
        return adminList;
    }

    @Override
    public Result adminLoginByPwd(LoginParam loginParam) {
        Map<String ,Object> resultMap = new HashMap<>();
        String phone = loginParam.getPhone();
        String password = MD5.getMD5(loginParam.getPassword());
        if (StringUtils.isBlank(password) || StringUtils.isBlank(phone)) {
            return Result.fail(100, "账号或者密码为空");
        }
        LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Admin::getPhone, phone).eq(Admin::getPassword, password).eq(Admin::getAuthority, "927360369");
        Admin Admin = am.selectOne(queryWrapper);
        if (Admin == null) {
            return Result.fail(100, "账号或者密码错误");
        }
        // 生成token
        String token = JWTUtil.createToken(phone);
        resultMap.put("token", token);
        resultMap.put("admin",Admin);
        // 存入redis并设置过期时间为10天
        redisUtil.set("admin-login:" + phone, Admin, 10, TimeUnit.DAYS);
        return Result.success(resultMap, "登录成功");
    }

    @Override
    public Result getAdminPage(PageParam pageParam) {
        IPage<Admin> iPage = new Page<>(pageParam.getPage(), pageParam.getPageSize());
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("authority", "927360369");
        if (!StringUtils.isBlank(pageParam.getMessage())) {
            queryWrapper.and(wq -> wq.like("name", pageParam.getMessage()).or().like("phone", pageParam.getMessage()).or().like("address", pageParam.getMessage()));
        }
        IPage<Admin> admin = am.selectPage(iPage, queryWrapper);
        return Result.success(admin, "加载成功!");
    }

    @Override
    public Result delAdmin(Integer id) {
        int isDelete = am.deleteById(id);
        if (isDelete > 0) {
            return Result.success(isDelete, "删除成功");
        }
        return Result.fail(100, "删除失败");
    }

    @Override
    public Result updateAdmin(Admin admin) {
        if (admin.getId() != null) {
            int update = am.updateById(admin);
            if (update > 0) {
                return Result.success(update, "修改成功");
            }
            return Result.fail(100, "修改失败");

        } else {
            admin.setAuthority("927360369");
            if (!am.existsUserByPhone(admin.getPhone())) {
                int insert = am.insert(admin);
                if (insert > 0) {
                    return Result.success(insert, "添加成功");
                }
                return Result.fail(100, "添加失败");
            } else {
                return Result.fail(100, "添加失败,用户已存在");
            }
        }
    }

    @Override
    public Result wxLogin(WxParam wxParam) {
        String phone = wxParam.getPhone();
        QueryWrapper queryWrapper = new QueryWrapper<Admin>()
                .eq("phone", phone)
                .select("open_id", "id");
        Admin admin1 = am.selectOne(queryWrapper);
        if (admin1 != null) {
            int id = admin1.getId();
            String openId = admin1.getOpenId();
            if (openId == null) {
                String openID = LoginUtil.toWxLogin(wxParam.getCode());
                Admin admin = new Admin()
                        .setId(id)
                        .setOpenId(openID);
                int update = am.updateById(admin);
                if (update > 0) {
                    // 生成token
                    String token = JWTUtil.createToken(phone);
                    // 存入redis并设置过期时间为10天
                    redisUtil.set("app-login:" + phone, admin, 10, TimeUnit.DAYS);
                    return Result.success(token, "修改成功");
                }
                return Result.fail(100, "修改失败");
            } else {
                // 生成token
                String token = JWTUtil.createToken(phone);
                // 存入redis并设置过期时间为10天
                redisUtil.set("app-login:" + phone, admin1, 10, TimeUnit.DAYS);
                return Result.success(token, "success");
            }
        } else {
            // 生成token
            String token = JWTUtil.createToken(phone);
            // 存入redis并设置过期时间为10天
            redisUtil.set("app-login:" + phone, new Admin().setPhone(phone), 10, TimeUnit.DAYS);
            return Result.success(token, "success");
        }

    }


    @Override
    public Result appLogin(LoginParam loginParam) {
        Map<String ,Object> resultMap = new HashMap<>();
        String phone = loginParam.getPhone();
        try {
            //验证码校验 校验失败 抛出异常
            ConvenientUtil.verifyCode(loginParam.getCode(), phone);
        } catch (ClapException e) {
            return Result.fail(e.getErrorCode(), e.getErrorMsg());
        }
        LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Admin::getPhone, phone);
        List<Admin> adminList = am.selectList(queryWrapper);
        List<String> addressList = new ArrayList<>();
        if (adminList.size() == 0) {
            LoginResult loginResult = new LoginResult();
            loginResult.setPhone(phone);
            loginResult.setName("群众");
            loginResult.setAddress("");
            loginResult.setAuthority("0");
            loginResult.setAddressList(addressList);
            // loginResult
            resultMap.put("loginResult", loginResult);
            // 生成token
            String token = JWTUtil.createToken(phone);
            resultMap.put("token", token);
            // 存入redis并设置过期时间为10天
            redisUtil.set("app-login:" + phone, loginResult, 10, TimeUnit.DAYS);
            return Result.success(resultMap, "success");
        }
        for (Admin admin : adminList) {
            addressList.add(admin.getAddress());
        }
        LoginResult loginResult = new LoginResult();
        loginResult.setPhone(phone);
        loginResult.setName(adminList.get(0).getName());
        loginResult.setAddress(adminList.get(0).getAddress());
        loginResult.setAuthority(adminList.get(0).getAuthority());
        loginResult.setAddressList(addressList);
        // loginResult
        resultMap.put("loginResult", loginResult);
        // 生成token
        String token = JWTUtil.createToken(phone);
        resultMap.put("token", token);
        // 存入redis并设置过期时间为10天
        redisUtil.set("app-login:" + phone, adminList.get(0), 10, TimeUnit.DAYS);
        return Result.success(resultMap, "success");
    }


    @Override
    public Result loginSendSms(String phone) {
        try {
            return Result.success(ConvenientUtil.sendSms(phone), "success");
        } catch (ClapException e) {
            return Result.fail(e.getErrorCode(), e.getErrorMsg());
        }

    }
}
